<script setup>
import { ref, watch } from 'vue'
import service from '@/utils/request'
import { useMessageStore } from '@/stores/MessageStore'

const searchQuery = ref('')
const searchResults = ref([])
const loading = ref(false)

// 监听搜索框内容变化
watch(searchQuery, (newValue) => {
  if (!newValue.trim()) {
    searchResults.value = []
  }
})

const handleSearch = async () => {
  if (!searchQuery.value.trim()) return

  loading.value = true
  try {
    const response = await service.get('/search', {
      params: {
        keyword: searchQuery.value,
      },
    })
    searchResults.value = response.data
    if (searchResults.value.length === 0) {
      useMessageStore().trigger('无搜索结果！', 'warning')
    }
  } catch (error) {
    console.error('Search error:', error)
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="d-flex flex-column align-center justify-center" style="height: 80vh">
    <h1 class="text-h3 mb-8">QAQ Search</h1>

    <!-- 搜索框 -->
    <v-card class="search-card" width="600">
      <v-text-field
        v-model="searchQuery"
        variant="outlined"
        density="comfortable"
        hide-details
        placeholder="搜索..."
        prepend-inner-icon="mdi-magnify"
        class="search-field"
        @keyup.enter="handleSearch"
      >
        <template v-slot:append>
          <v-btn color="primary" variant="text" :loading="loading" @click="handleSearch">
            搜索
          </v-btn>
        </template>
      </v-text-field>
    </v-card>

    <!-- 搜索结果 -->
    <v-list v-if="searchResults.length" class="mt-4" width="600">
      <v-list-item v-for="(result, index) in searchResults" :key="index">
        <template v-slot:title>
          <div v-html="result.title"></div>
        </template>
        <template v-slot:subtitle>
          <div v-html="result.content"></div>
        </template>
      </v-list-item>
    </v-list>
  </div>
</template>

<style scoped>
.search-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-field {
  font-size: 16px;
}
</style>
